#include "types.h"
#include "console.h"

// 优化的数字转换，避免除法（使用查表）
static const char* hex_digits_lower = "0123456789abcdef";
static const char* hex_digits_upper = "0123456789ABCDEF";

// 快速整数转字符串（十进制）
static int itoa_dec(int32 num, char *buf) {
    int i = 0;
    int is_negative = 0;
    int fuck = 0;
    // 特殊处理最小负数：-2147483648
    if (num == -2147483648) {
        const char* min_str = "-2147483648";
        int j = 0;
        while (min_str[j] != '\0') {
            buf[i++] = min_str[j++];
        }
        return i;
    }

    // 处理负数
    if (num < 0) {
        is_negative = 1;
        num = -num;
    }

    // 特殊情况：0
    if (num == 0) {
        buf[i++] = '0';
    } else {
        // 转换数字（逆序）
        while (num > 0) {
            buf[i++] = '0' + (num % 10);
            num /= 10;
        }
    }
    
    // 添加负号
    if (is_negative) {
        buf[i++] = '-';
    }
    
    // 反转字符串
    for (int j = 0; j < i / 2; j++) {
        char temp = buf[j];
        buf[j] = buf[i - j - 1];
        buf[i - j - 1] = temp;
    }
    
    return i;
}

// 无符号整数转字符串（任意进制）
static int utoa_base(uint32 num, uint32 base, int uppercase, char *buf) {
    int i = 0;
    const char *digits = uppercase ? hex_digits_upper : hex_digits_lower;
    
    if (num == 0) {
        buf[i++] = '0';
    } else {
        while (num > 0) {
            buf[i++] = digits[num % base];
            num /= base;
        }
    }
    
    // 反转字符串
    for (int j = 0; j < i / 2; j++) {
        char temp = buf[j];
        buf[j] = buf[i - j - 1];
        buf[i - j - 1] = temp;
    }
    
    return i;
}

// 输出数字到控制台
void print_int(int32 num) {
    char buf[32];
    int len = itoa_dec(num, buf);
    console_write(buf, len);
}

void print_uint(uint32 num, uint32 base, int uppercase) {
    char buf[32];
    int len = utoa_base(num, base, uppercase, buf);
    console_write(buf, len);
}

void print_pointer(uintptr_t ptr) {
    console_puts("0x");
    print_uint(ptr, 16, 0);
}
